import 'package:flutter/material.dart';
import 'package:schedule_self_client/api/user_center/login_resp.dart';
import 'package:schedule_self_client/api/user_center/user_api.dart';
import 'package:schedule_self_client/api/user_center/user_info_qry_resp.dart';
import 'package:schedule_self_client/domain/user_info_manager.dart';

class LoginInfo with ChangeNotifier {
  UserInfo? userInfo;

  LoginInfo(this.userInfo) {
    notifyListeners();
  }

  init() async {
    userInfo = await UserInfo.initWithCache();
  }

  Future<void> login(
      LoginResp? loginResp, UserInfoQryResp? userInfoQryResp) async {
    final token = loginResp?.data.tokenValue;
    userInfo = UserInfo.initBy(userInfoQryResp?.data, token);
    UserInfo.cache(
        userInfoQryResp?.data.username,
        userInfoQryResp?.data.nickName,
        userInfoQryResp?.data.avatarUrl,
        userInfoQryResp?.data.email,
        token);
    notifyListeners();
  }

  Future<void> cleanOldCache() async {
    await UserInfo.clearCache();
    userInfo = null;
    notifyListeners();
  }

  Future<void> logout() async {
    await UserApi.logout();
    await UserInfo.clearCache();
    userInfo = null;
    notifyListeners();
  }
}
